package org.frog.sgs.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

/**
 * @author duanxiangqi
 * @date 2012-10-19
 */
public enum SgsUtils {
	instance;

	private static Logger logger = Logger.getLogger(SgsUtils.class);

	/**
	 * load xml file
	 * 
	 * @param path
	 * @return
	 * @throws DocumentException
	 * @throws IOException
	 */
	public Document loadXml(String path) throws DocumentException, IOException {
		InputStream is = ClassLoader.getSystemResourceAsStream(path);
		Document document = new SAXReader().read(is);
		is.close();
		return document;
	}

	/**
	 * copy list to list
	 * 
	 * @param <T>
	 * @param list
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> List<T> copy(List<T> list) {
		List<T> allCopy = new ArrayList<T>();
		for (T t : list) {
			try {
				T copy = (T) t.getClass().newInstance();
				BeanUtils.copyProperties(copy, t);
				allCopy.add(copy);
			} catch (Exception e) {
				logger.error("Basic Copy出错：" + t, e);
			}
		}
		return allCopy;
	}

	public int byte2int(byte[] b) {
		return (b[0] << 24) + (b[1] << 16) + (b[2] << 8) + (b[3] & 0xFF);
	}

	public byte[] int2byte(int value) {
		byte[] b = new byte[4];
		for (int i = 0; i < 4; i++) {
			int offset = (b.length - 1 - i) * 8;
			b[i] = (byte) ((value >>> offset) & 0xFF);
		}
		return b;
	}
}
